package com.booktrading.controller;

import com.booktrading.model.Book;
import com.booktrading.model.User;
import com.booktrading.service.BookService;
import com.booktrading.service.UserService;
import com.booktrading.util.FileUploadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/book")
public class BookController {

    private static final Logger logger = LoggerFactory.getLogger(BookController.class);

    @Autowired
    private BookService bookService;
    
    @Autowired
    private UserService userService;
    
    @Value("${file.upload.dir}")
    private String fileUploadDir;
    
    /**
     * 书籍列表页
     */
    @GetMapping("/list")
    public String listPage(Model model,
                          @RequestParam(value = "category", required = false) String category,
                          @RequestParam(value = "keyword", required = false) String keyword,
                          @RequestParam(value = "minPrice", required = false) Double minPrice,
                          @RequestParam(value = "maxPrice", required = false) Double maxPrice,
                          @RequestParam(value = "sort", required = false) String sort) {
        
        List<Book> books;
        
        if (category != null && !category.isEmpty()) {
            books = bookService.getBooksByCategory(category);
            model.addAttribute("categoryFilter", category);
        } else if (keyword != null && !keyword.isEmpty()) {
            books = bookService.searchBooks(keyword);
            model.addAttribute("keywordFilter", keyword);
        } else if (minPrice != null && maxPrice != null) {
            books = bookService.getBooksByPriceRange(minPrice, maxPrice);
            model.addAttribute("minPriceFilter", minPrice);
            model.addAttribute("maxPriceFilter", maxPrice);
        } else {
            books = bookService.getAllOnSaleBooks();
        }
        
        if (sort != null && !sort.isEmpty()) {
            String[] sortParams = sort.split(",");
            if (sortParams.length == 2) {
                String sortField = sortParams[0];
                String sortDirection = sortParams[1];
                
                if ("price".equals(sortField)) {
                    if ("asc".equals(sortDirection)) {
                        books.sort(Comparator.comparing(Book::getPrice));
                    } else if ("desc".equals(sortDirection)) {
                        books.sort(Comparator.comparing(Book::getPrice).reversed());
                    }
                } else if ("createdTime".equals(sortField)) {
                    books.sort(Comparator.comparing(Book::getCreateTime).reversed());
                }
            }
        }
        
        model.addAttribute("books", books);
        
        return "book/list";
    }
    
    /**
     * 书籍详情页
     */
    @GetMapping("/detail/{id}")
    public String detailPage(@PathVariable("id") Long id, Model model) {
        Book book = bookService.getBookById(id);
        
        if (book == null) {
            return "redirect:/booktrading/book/list";
        }
        
        bookService.incrementViews(id);
        
        model.addAttribute("book", book);
        
        return "book/detail";
    }
    
    /**
     * 发布书籍页面
     */
    @GetMapping("/publish")
    public String publishPage() {
        return "book/publish";
    }
    
    /**
     * 发布书籍处理
     */
    @PostMapping("/publish")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> publish(@RequestBody Book book) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.getUserByUsername(username);
            
            book.setSellerId(currentUser.getId());
            book.setSellerName(currentUser.getUsername());
            
            Book publishedBook = bookService.publishBook(book);
            
            if (publishedBook != null && publishedBook.getId() != null) {
                result.put("success", true);
                result.put("message", "发布成功");
                result.put("bookId", publishedBook.getId());
                result.put("redirectUrl", "/book/detail/" + publishedBook.getId());
            } else {
                result.put("success", false);
                result.put("message", "发布失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "发布失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 上传书籍图片
     */
    @PostMapping("/upload-image")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> uploadImage(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        
        if (file.isEmpty()) {
            result.put("success", false);
            result.put("message", "请选择要上传的图片");
            return ResponseEntity.ok(result);
        }
        
        String contentType = file.getContentType();
        if (contentType == null || (!contentType.startsWith("image/jpeg") && !contentType.startsWith("image/png"))) {
            result.put("success", false);
            result.put("message", "只支持JPG和PNG格式的图片");
            return ResponseEntity.ok(result);
        }
        
        if (file.getSize() > 2 * 1024 * 1024) {
            result.put("success", false);
            result.put("message", "图片大小不能超过2MB");
            return ResponseEntity.ok(result);
        }
        
        try {
            String imageUrl = FileUploadUtil.saveFile(file, fileUploadDir);
            
            result.put("success", true);
            result.put("message", "上传成功");
            result.put("imageUrl", imageUrl);
            
        } catch (IOException e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "上传失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 下架书籍
     */
    @PostMapping("/remove/{id}")
    @ResponseBody
    public Map<String, Object> removeBook(@PathVariable("id") Long id) {
        Map<String, Object> result = new HashMap<>();

        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.getUserByUsername(username);

            Book book = bookService.getBookById(id);

            if (book == null) {
                result.put("success", false);
                result.put("message", "书籍不存在");
                return result;
            }

            if (!book.getSellerId().equals(currentUser.getId())) {
                result.put("success", false);
                result.put("message", "无权下架他人书籍");
                return result;
            }

            // 更新书籍状态为已下架(0)
            boolean success = bookService.updateBookStatus(id, 0);

            if (success) {
                result.put("success", true);
                result.put("message", "下架成功");
            } else {
                result.put("success", false);
                result.put("message", "下架失败，请稍后重试");
            }
        } catch (Exception e) {
            logger.error("下架书籍失败", e);
            result.put("success", false);
            result.put("message", "系统错误，请稍后重试");
        }

        return result;
    }
    
    /**
     * 上架书籍
     */
    @PostMapping("/relist/{id}")
    @ResponseBody
    public Map<String, Object> relistBook(@PathVariable("id") Long id) {
        Map<String, Object> result = new HashMap<>();

        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.getUserByUsername(username);

            Book book = bookService.getBookById(id);

            if (book == null) {
                result.put("success", false);
                result.put("message", "书籍不存在");
                return result;
            }

            if (!book.getSellerId().equals(currentUser.getId())) {
                result.put("success", false);
                result.put("message", "无权上架他人书籍");
                return result;
            }

            // 更新书籍状态为在售(1)
            boolean success = bookService.updateBookStatus(id, 1);

            if (success) {
                result.put("success", true);
                result.put("message", "上架成功");
            } else {
                result.put("success", false);
                result.put("message", "上架失败，请稍后重试");
            }
        } catch (Exception e) {
            logger.error("上架书籍失败", e);
            result.put("success", false);
            result.put("message", "系统错误，请稍后重试");
        }

        return result;
    }
    
    /**
     * 编辑书籍页面
     */
    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable("id") Long id, Model model) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.getUserByUsername(username);
        
        Book book = bookService.getBookById(id);
        
        if (book == null) {
            return "redirect:/booktrading/book/list";
        }
        
        // 验证是否是书籍的卖家
        if (!book.getSellerId().equals(currentUser.getId())) {
            return "redirect:/booktrading/book/list";
        }
        
        model.addAttribute("book", book);
        
        return "book/edit";
    }
    
    /**
     * 更新书籍信息
     */
    @PostMapping("/update")
    @ResponseBody
    public Map<String, Object> update(@RequestBody Book book) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.getUserByUsername(username);
            
            // 验证是否是书籍的卖家
            Book existingBook = bookService.getBookById(book.getId());
            if (existingBook == null || !existingBook.getSellerId().equals(currentUser.getId())) {
                result.put("success", false);
                result.put("message", "无权修改此书籍");
                return result;
            }
            
            // 保留原有的不可修改字段
            book.setSellerId(existingBook.getSellerId());
            book.setSellerName(existingBook.getSellerName());
            book.setStatus(existingBook.getStatus());
            book.setViews(existingBook.getViews());
            book.setCreateTime(existingBook.getCreateTime());
            
            boolean success = bookService.updateBook(book);
            
            if (success) {
                result.put("success", true);
                result.put("message", "更新成功");
            } else {
                result.put("success", false);
                result.put("message", "更新失败");
            }
        } catch (Exception e) {
            logger.error("更新书籍失败", e);
            result.put("success", false);
            result.put("message", "系统错误，请稍后重试");
        }
        
        return result;
    }
    
    /**
     * 删除书籍
     */
    @PostMapping("/delete/{id}")
    @ResponseBody
    public Map<String, Object> deleteBook(@PathVariable("id") Long id) {
        Map<String, Object> result = new HashMap<>();

        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.getUserByUsername(username);

            Book book = bookService.getBookById(id);

            if (book == null) {
                result.put("success", false);
                result.put("message", "书籍不存在");
                return result;
            }

            if (!book.getSellerId().equals(currentUser.getId())) {
                result.put("success", false);
                result.put("message", "无权删除他人书籍");
                return result;
            }

            boolean success = bookService.deleteBook(id);

            if (success) {
                result.put("success", true);
                result.put("message", "删除成功");
            } else {
                result.put("success", false);
                result.put("message", "删除失败，请稍后重试");
            }
        } catch (Exception e) {
            logger.error("删除书籍失败", e);
            result.put("success", false);
            result.put("message", "系统错误，请稍后重试");
        }

        return result;
    }
} 